<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <link rel="stylesheet" href="./styles.css">
    <link rel="stylesheet" href="https://unpkg.com/vue-simple-notify/dist/vue-simple-notify.min.css">
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <script src="https://unpkg.com/vue-simple-notify/dist/vue-simple-notify.min.js"></script>
    <script src="/socket.io/socket.io.js"></script>
</head>


<body>
    <div id="app">
        <section class="alerts">
            <alerts :items="alerts"></alerts>
        </section>
        <section class="chat">
            <h1>{{title}} 当前用户：{{username}}</h1>
            <form action="">
                <input v-model="text" type="text" />
                <button @click.prevent="sendChatMessage">发送</button>
            </form>
            <p>
            <ul>
                <li v-for="(item,index) in message" :key="index">
                    <strong>{{item.sender}}:</strong> {{item.message}}
                </li>
            </ul>
            </p>
        </section>
    </div>
    <script>
        Vue.component('alerts', VueSimpleNotify.VueSimpleNotify);
        var app = new Vue({
            el: '#app',
            data: {
                title: 'webSocket Test',
                text: '',
                username: '',
                message: [],
                alerts: [],
                socket: { chat: null, alerts: null }
            },
            methods: {
                sendChatMessage() {
                    this.socket.chat.emit('chatToServer', { sender: this.username, message: this.text });
                    this.text = '';
                },
                receiveChatMessage(msg) {
                    this.message.push(msg)
                },
                receiveAlertMessage(msg) {
                    this.alerts.push(msg)
                    console.log(this.alerts)
                }
            },
            created() {
                this.username = prompt('your username:')
                this.socket.chat = io('http://localhost:3000/chat');
                this.socket.chat.on('chatToClient', (msg) => {
                    this.receiveChatMessage(msg)
                })

                this.socket.alerts = io('http://localhost:3000/alert');
                this.socket.alerts.on('alertToClient', (msg) => {
                    this.receiveAlertMessage(msg)
                })
            }
        });
    </script>
</body>

</html>